Sunday, July 18, 2004

ugly super class-method call...

Yesterday I stumbled on a funny problem :)

Task:
call the original class-method extended by another class-method in a subclass.

Logical Answer:
use the super function.

The Problem:
considering that the way "super" is called, is not the most beautiful feature of the Python language (this is sed to be a wart by some). this situation created a code far uglier. to be honest, I hate this solution but I can't seem to come up with a better one... does anyone have any suggestions?

the problem is that there are situations (though quite rare, or even unlikely) when this code will break!

see the example below for more details...


a full example:

 
class SomeBaseClass(object):
'''
'''
def meth(self):
'''
'''
print '###', self, self.__class__
 
 
class _MetaClass(SomeBaseClass, type):
'''
'''
def __init__(cls, name, bases, ns):
'''
'''
if 'meth' in ns:
setattr(cls, 'meth', classmethod(ns['meth']))
super(_MetaClass, cls).__init__(name, bases, ns)
 
 
class SomeClass(object):
'''
'''
__metaclass__ = _MetaClass
 
 
class SomeOtherClass(object):
'''
'''
__metaclass__ = _MetaClass
 
def meth(cls):
'''
'''
print 'this is a class-method...'
# and here is the problematic line of code:
super(cls.__class__, cls).meth() # or super(cls.__metaclass__, cls).meth()
 
 
if __name__ == '__main__':
 
basic_obj = SomeBaseClass()
some_other_obj = SomeOtherClass()
 
basic_obj.meth()
SomeClass.meth()
some_other_obj.meth()
 
# vim: set ts=4 sw=4 nowrap :


metaclass_examle.py

if anyone is interested, this is a simplified version of the structure of a module (pli.event.event or a shorthand pli.event), part of the pli library.

this was originaly posted here.

0 Comments:

Post a Comment

<< Home